package com.syh.jn.scm.service.impl.upstream.finance;

import cn.redscarf.commons.util.other.ExtAssert;
import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.upstream.entity.finance.UpSalesInvoice;
import com.syh.jn.scm.domain.upstream.entity.finance.UpSalesInvoiceEvent;
import com.syh.jn.scm.domain.upstream.repository.finance.UpSalesInvoiceRepository;
import com.syh.jn.scm.dto.upstream.finance.UpSalesInvoiceMto;
import com.syh.jn.scm.dto.upstream.finance.UpSalesInvoiceSto;
import com.syh.jn.scm.dto.upstream.finance.UpSalesInvoiceVo;
import com.syh.jn.scm.service.api.upstream.finance.UpSalesInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 上游销项发票
 */
@Service
@Transactional
public class UpSalesInvoiceServiceImpl extends AbstractServiceImpl<UpSalesInvoiceSto, UpSalesInvoiceMto, UpSalesInvoiceVo, UpSalesInvoice, Long> implements UpSalesInvoiceService {
  @Autowired
  UpSalesInvoiceRepository upSalesInvoiceRepository;

  @Override
  protected AggregateRepository<UpSalesInvoice, Long> getAggregateRepository() {
    return upSalesInvoiceRepository;
  }

  @Override
  public Long save(UpSalesInvoiceSto sto) {
    ExtAssert.notNull(sto, "对象为空");
//    ValidationUtils.validate(sto);

    UpSalesInvoice upSalesInvoice = new UpSalesInvoice(sto);
    Long id = upSalesInvoiceRepository.add(upSalesInvoice);
    this.publicEvent(UpSalesInvoiceEvent.buildCreated(new Object[]{upSalesInvoice}));
    return id;
  }

  @Override
  public void update(UpSalesInvoiceMto mto) {
    ExtAssert.notNull(mto, "对象为空");
//    ValidationUtils.validate(mto);

    UpSalesInvoice invoice = getInvoiceById(mto.getId());
    invoice.modify(mto);
    upSalesInvoiceRepository.update(invoice);
  }

  @Override
  public void delete(Long id) {
    UpSalesInvoice invoice = getInvoiceById(id);
    invoice.destroy();
    upSalesInvoiceRepository.remove(invoice);
    this.publicEvent(UpSalesInvoiceEvent.buildDestroy(new Object[]{invoice}));
  }

  /**
   * 根据id获取发票信息
   * @param id
   * @return
   */
  private UpSalesInvoice getInvoiceById(Long id) {
    ExtAssert.notNull(id, "id为空");

    UpSalesInvoice invoice = upSalesInvoiceRepository.getById(id);
    ExtAssert.notNull(invoice, "对象为空");

    return invoice;
  }
}
